//
//  EFengComposeTextView.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/3/7.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "EFengComposeTextView.h"
#import "NSString+CBExtension.h"

#define kViewRoundedCornerRadius 6.0f
#define kMaxCharacterCount 30
#define kFontName @"[z] Arista"
#define kPlaceholderText @"请输入个人签名..."

#define KNormalTextColor RGBCOLOR(0x32, 0x32, 0x32)
#define KPlacehoderTextColor RGBCOLOR(0xd4, 0xd4, 0xd4)

@interface EFengComposeTextView ()<UITextViewDelegate>

{
    UILabel *characterCountLabel;
}

@end

@implementation EFengComposeTextView


- (void)dealloc
{
    //    NSLog(@"CHSCharacterCountTextView dealloc");
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        // Setup the view
        [self setupView];
    }
    return self;
}

//-(id)initWithCoder:(NSCoder *)aDecoder {
//
//	if( (self = [super initWithCoder:aDecoder]) ) {
//
//		// Setup the view
//		[self setupView];
//	}
//	return self;
//}

- (NSAttributedString *)attrText
{
    return [self.text cookEmotionStringWithFont:Font18 textColor:RGBCOLORWITH16COLOR(0x323232)];
}

- (void)setAttrText:(NSAttributedString *)attrText
{
    self.messageTextView.attributedText = self.attrText;
}

-(void)setText:(NSString *)text
{
    _text = [text copy];
    
    //bug 6300 fixed by 荣则兵
    self.messageTextView.text = text;
    [self.messageTextView setTextColor:KNormalTextColor];
    [self updateText:text];
    self.showingPlaceholder = NO;
    
}

- (void)updateText:(NSString *)text
{
    _text = text;
    NSInteger characterCount = self.MAXCHARACTERCOUNT - [[self.messageTextView text] length];
    if (characterCount >= 0) {
        [characterCountLabel setText:[NSString stringWithFormat:@"%zd", characterCount]];
    }else {
        [characterCountLabel setText:@"0"];
    }
    self.showingPlaceholder = NO;
    [self.messageTextView setTextColor:KNormalTextColor];
    
}
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */

- (void)setPlaceHoldText:(NSString *)placeHoldText
{
    _placeHoldText = [placeHoldText copy];
    self.messageTextView.text = placeHoldText;
    [self.messageTextView setTextColor:KPlacehoderTextColor];
    self.showingPlaceholder = YES;
}

- (void)setMAXCHARACTERCOUNT:(NSInteger)MAXCHARACTERCOUNT
{
    _MAXCHARACTERCOUNT = MAXCHARACTERCOUNT;
    [characterCountLabel setText:[NSString stringWithFormat:@"%zd", self.MAXCHARACTERCOUNT]];
}

#pragma mark - Private
-(void)setupView {
    // ****** README ********
    // Sometimes the font file name will be different than the embedded font name that the iOS system is using as it's key descriptior
    // So you'll have to print the available fonts and see which one font your looking for.
    // Print the available fonts
    //NSLog(@"Available Font Families: %@", [UIFont familyNames]);
    
    // Set rounded corners on the text view
    [self.layer setCornerRadius:kViewRoundedCornerRadius];
    
    // Set showing a placeholder by default
    self.showingPlaceholder = YES;
    
    // Add the text view
    self.messageTextView = [[UITextView alloc] initWithFrame:self.bounds];
    //	[messageTextView setAutocorrectionType:UITextAutocorrectionTypeNo];
    [self.messageTextView setReturnKeyType:UIReturnKeyDone];
    [self.messageTextView.layer setCornerRadius:kViewRoundedCornerRadius];
    //	[messageTextView setBackgroundColor:ClearColor];
    [self.messageTextView setText:kPlaceholderText];
    self.placeHoldText = kPlaceholderText;
    //	[messageTextView setTextColor:[UIColor lightGrayColor]];
    [self.messageTextView setTextColor:KPlacehoderTextColor];
    
    self.messageTextView.delegate = self;
    [self.messageTextView setFont:Font14];
    [self addSubview:self.messageTextView];
    
    self.textFont = Font14;
    // Set the max character count
    self.MAXCHARACTERCOUNT = kMaxCharacterCount;
    
    // Add a character label
    float characterCountLabelWidth = 30.0f;
    float characterCountLabelHeight =  18.0f;
    characterCountLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width-characterCountLabelWidth-3, self.frame.size.height-characterCountLabelHeight, characterCountLabelWidth, characterCountLabelHeight)];
    [characterCountLabel setTextAlignment:UITextAlignmentRight];
    [characterCountLabel setFont:[UIFont systemFontOfSize:14.0f]];
    [characterCountLabel setBackgroundColor:[UIColor clearColor]];
    //    characterCountLabel.textColor = [UIColor lightGrayColor];
    characterCountLabel.textColor = RGBCOLOR(0xd4, 0xd4, 0xd4);
    [characterCountLabel setText:[NSString stringWithFormat:@"%zd", self.MAXCHARACTERCOUNT]];
    [self addSubview:characterCountLabel];
}

- (void)setTextFont:(UIFont *)textFont
{
    _textFont = textFont;
    self.messageTextView.font = textFont;
    [self setPlaceHoldText:self.placeHoldText];
    [self setText:self.text];
}

-(void)setEditEnable:(BOOL)isEditEnable
{
    [self.messageTextView setEditable:isEditEnable];
    CGRect frame = self.bounds;
    frame.origin.x = frame.origin.x + 10;
    frame.origin.y = frame.origin.y + 10;
    frame.size.width = frame.size.width - 20;
    frame.size.height = frame.size.height - 20;
    
    self.messageTextView.frame = frame;
    if(!isEditEnable){
        //   bug 6040
        characterCountLabel.hidden=YES;
    }
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    float characterCountLabelWidth = 35.0f;
    float characterCountLabelHeight =  18.0f;
    characterCountLabel.frame = CGRectMake(self.frame.size.width-characterCountLabelWidth-3, self.frame.size.height-characterCountLabelHeight, characterCountLabelWidth, characterCountLabelHeight);
    self.messageTextView.frame = self.bounds;
    
}

#pragma mark - UITextView Delegate Methods
-(void)textViewDidBeginEditing:(UITextView *)textView {
    
    // Check if it's showing a placeholder, remove it if so
    if(self.showingPlaceholder) {
        [textView setText:@""];
        [textView setTextColor:KNormalTextColor];
        
        self.showingPlaceholder = NO;
    }
    
    if ([self.eFengComposeTextViewDelegate respondsToSelector:@selector(eFengComposeTextViewDidBeginEditing:)]) {
        [self.eFengComposeTextViewDelegate eFengComposeTextViewDidBeginEditing:self];
    }
}

-(void)textViewDidEndEditing:(UITextView *)textView {
    
    // Check the length and if it should add a placeholder
    if([[textView text] length] == 0) {
        [self setPlaceHoldText:self.placeHoldText];
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    // if the user clicked the return key
    
    if ([text isEqualToString: @"\n"]) {
        // Hide the keyboard
        [textView resignFirstResponder];
        
        // Also return if its showing a placeholder
        if(self.showingPlaceholder) {
            return NO;
        }
        
        // Notify the delegate
        
        if(self.eFengComposeTextViewDelegate && [self.eFengComposeTextViewDelegate respondsToSelector:@selector(eFengComposeTextView:postedMessage:)]) {
            [self.eFengComposeTextViewDelegate eFengComposeTextView:self postedMessage:self.messageTextView.text];
        }
        
        return NO ;
    }
    return YES ;
}

- (void)textViewDidChange:(UITextView *)textView {
    if (textView.text.length > self.MAXCHARACTERCOUNT) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            textView.text = [textView.text substringToIndex:self.MAXCHARACTERCOUNT];
            [self updateText:textView.text];
        });
    }
    if (textView.text.length <= self.MAXCHARACTERCOUNT) {
        // Update the character count
        [self updateText:textView.text];
    }
    [self.messageTextView scrollRangeToVisible:textView.selectedRange];
    if ([self.eFengComposeTextViewDelegate respondsToSelector:@selector(eFengComposeTextViewDidChange:)] && self.eFengComposeTextViewDelegate != nil) {
        [self.eFengComposeTextViewDelegate eFengComposeTextViewDidChange:self];
        
    }
}


- (void)setSelectedRange:(NSRange)selectedRange
{
    self.messageTextView.selectedRange = selectedRange;
}

- (NSRange)selectedRange
{
    return [self.messageTextView selectedRange];
}
- (BOOL)isFirstResponder
{
    [super isFirstResponder];
    return [self.messageTextView isFirstResponder];
}
- (BOOL)resignFirstResponder
{
    [super resignFirstResponder];
    return [self.messageTextView resignFirstResponder];
}


@end
